package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.common.collect.Lists;
import com.zhijian.medical.dao.local.StudyClassMapper;
import com.zhijian.medical.entity.UploadParam;
import com.zhijian.medical.entity.dto.PersonDto;
import com.zhijian.medical.entity.po.Assessment;
import com.zhijian.medical.entity.po.StudyClass;
import com.zhijian.medical.entity.vo.request.StudyClassSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.StudyClassSearchVo;
import com.zhijian.medical.entity.vo.response.StudyClassVo;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.AssessmentService;
import com.zhijian.medical.service.StudyClassService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.Page;
import com.zhijian.medical.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 学习班业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2023-12-07 19:45:41
 */
@Slf4j
@Service
public class StudyClassServiceImpl implements StudyClassService {

    @Autowired
    private StudyClassMapper mapper;

    @Autowired
    private UploadParam uploadParam;

    @Autowired
    private AssessmentService assessmentService;

    @Override
    public StudyClass selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public StudyClassVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(StudyClass studyClass) {
        Date now = new Date();
        studyClass.setCreateTime(now);
        studyClass.setUpdateTime(now);
        return mapper.insert(studyClass) > 0 ? studyClass.getId() : 0L;
    }

    @Override
    public boolean update(StudyClass studyClass) {
        Date now = new Date();
        studyClass.setUpdateTime(now);
        return mapper.updateByPrimaryKey(studyClass) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(StudyClass record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public Integer count(StudyClassSearchVo studyClassSearchVo) {
        return mapper.count(studyClassSearchVo);
    }

    @Override
    public List<StudyClassVo> selectList(StudyClassSearchVo studyClassSearchVo) {
        List<StudyClassVo> studyClassVos = mapper.selectList(studyClassSearchVo);
        if (CollectionUtil.isEmpty(studyClassVos)) {
            return Collections.emptyList();
        }
        //当前登录用户ID
        Long currentUserId = CurrentUserHolder.getUser().getId();
        for (StudyClassVo studyClassVo : studyClassVos) {
            String doPersonIds = studyClassVo.getDoPersonIds();
            //这个学习班的做题人
            if (StringUtils.isNotBlank(doPersonIds)) {
                //包含就是1，不包含就是0
                List<String> doPersonIdList = Arrays.asList(doPersonIds.split(","));
                studyClassVo.setWeatherAlreadyEnroll(doPersonIdList.contains(currentUserId + "") ? 1 : 0);
                //转成数组
                studyClassVo.setDoPersonIdList(doPersonIdList);
            } else {
                //没有人，肯定不包含
                studyClassVo.setWeatherAlreadyEnroll(0);
            }
        }
        return studyClassVos;
    }

    @Override
    public Page<StudyClassVo> selectPage(StudyClassSearchVo studyClassSearchVo) {
        //先直接查总数
        int count = count(studyClassSearchVo);
        //分页
        Page<StudyClassVo> page = new Page<>(true, count, studyClassSearchVo.getPageNum(), studyClassSearchVo.getPageSize());
        studyClassSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<StudyClassVo> responseVos = this.selectList(studyClassSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<StudyClass> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public boolean save(StudyClassSaveOrUpdateVo studyClassSaveOrUpdateVo) {
        StudyClass studyClass = new StudyClass();
        BeanUtils.copyProperties(studyClassSaveOrUpdateVo, studyClass);
        PersonDto user = CurrentUserHolder.getUser();
        studyClass.setCreateUserId(user.getId());
        studyClass.setCreateUserName(user.getName());
        Long id = this.insert(studyClass);
        //生成个二维码
        String qrByAssessmentId = this.createQrByAssessmentId(id);
        this.updateByPrimaryKeySelective(StudyClass.builder()
                .id(id)
                .qrFilePath(qrByAssessmentId)
                .build());
        return id != 0;
    }

    @Override
    public boolean modify(StudyClassSaveOrUpdateVo studyClassSaveOrUpdateVo) {
        StudyClass oldStudyClass = this.selectById(studyClassSaveOrUpdateVo.getId());
        AssertUtil.notNull(oldStudyClass, "此数据不存在或者已被删除");
        oldStudyClass.setName(studyClassSaveOrUpdateVo.getName());
        oldStudyClass.setPosition(studyClassSaveOrUpdateVo.getPosition());
        oldStudyClass.setStartTime(studyClassSaveOrUpdateVo.getStartTime());
        oldStudyClass.setEndTime(studyClassSaveOrUpdateVo.getEndTime());
        return this.update(oldStudyClass);
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean enroll(Long id) {
        StudyClass studyClass = this.selectById(id);
        AssertUtil.notNull(studyClass, "此数据不存在或者已被删除");
        String doPersonIds = studyClass.getDoPersonIds();
        List<Long> personIdList = Lists.newArrayList();
        //把做题人的用户ID塞进去
        if (StringUtils.isNotBlank(doPersonIds)) {
            personIdList = Arrays.stream(doPersonIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        }
        personIdList.add(CurrentUserHolder.getUser().getId());
        doPersonIds = StrUtil.join(",", personIdList);
        //修改
        this.updateByPrimaryKeySelective(StudyClass.builder()
                .id(studyClass.getId())
                .doPersonIds(doPersonIds)
                .build());
        //如果已经有了考核，就把这个人也塞进去
        Assessment assessment = assessmentService.selectByStudyClassId(studyClass.getId());
        if (Objects.nonNull(assessment)) {
            //修改
            assessmentService.updateByPrimaryKeySelective(Assessment.builder()
                    .id(assessment.getId())
                    .doPersonIds(doPersonIds)
                    .build());
        }
        return true;
    }

    /**
     * 根据学习班ID生成二维码
     *
     * @param assessmentId
     * @return
     */
    private String createQrByAssessmentId(Long assessmentId) {
        //文件储存路径
        String storePath = uploadParam.getStorePath();
        // 生成指定url对应的二维码到文件，宽和高都是300像素
        String realPath = String.format("%s%s.jpg", storePath, assessmentId);
        //内容
        String content = String.format("https://njglyy.zhijianiot.com/register?assessmentId=%s", assessmentId);
        QrCodeUtil.generate(content, 300, 300, FileUtil.file(realPath));
        return String.format("%s%s", uploadParam.getUrlPath(), String.format("%s.jpg", assessmentId));
    }
}